<template>
  <el-dialog
    :title="title"
    v-model="dialogVisible"
    width="800px"
    append-to-body
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      v-loading="loading"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户名">
            <span>{{ form.userId?.username || "-" }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="真实姓名">
            <span>{{ form.realName || "-" }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="身份证号">
            <span>{{ form.idNumber || "-" }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="身份证正面">
            <el-image
              v-if="form.idCardFront"
              style="width: 200px; height: 125px"
              :src="form.idCardFront"
              fit="cover"
              :preview-src-list="[form.idCardFront]"
            />
            <span v-else>无图片</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="身份证背面">
            <el-image
              v-if="form.idCardBack"
              style="width: 200px; height: 125px"
              :src="form.idCardBack"
              fit="cover"
              :preview-src-list="[form.idCardBack]"
            />
            <span v-else>无图片</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="电子签名">
            <el-image
              v-if="form.signature"
              style="width: 200px; height: 125px"
              :src="form.signature"
              fit="cover"
              :preview-src-list="[form.signature]"
            />
            <span v-else>无图片</span>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="!isShow">
          <el-form-item label="审核备注" prop="remarks">
            <el-input
              v-model="form.remarks"
              type="textarea"
              :rows="3"
              :placeholder="
                isApproved ? '请输入审核备注（可选）' : '请输入拒绝原因（必填）'
              "
              :disabled="isShow"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button
          v-if="!isShow"
          type="danger"
          :loading="loading"
          @click="handleVerify(false)"
        >
          拒 绝
        </el-button>
        <el-button
          v-if="!isShow"
          type="primary"
          :loading="loading"
          @click="handleVerify(true)"
        >
          通 过
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
/**
 * 实名认证审核对话框
 */
import { defineComponent, ref, reactive, toRefs } from "vue";
import { messageSuccess, messageError } from "@/action/MessagePrompt.js";
import verificationsApi from "@/http/verifications.js";
import { ElMessageBox } from "element-plus";

export default defineComponent({
  name: "VerifyDialog",
  setup() {
    const formRef = ref(null);
    const state = reactive({
      dialogVisible: false,
      loading: false,
      title: "",
      isShow: false,
      isApproved: true,
      form: {
        remarks: "",
      },
      rules: {
        remarks: [
          { required: false, message: "请输入审核备注", trigger: "blur" },
          {
            min: 2,
            max: 200,
            message: "长度在 2 到 200 个字符",
            trigger: "blur",
          },
        ],
      },
    });

    /** 初始化数据 */
    function initData(visible, row, querys) {
      state.dialogVisible = visible;
      state.isShow = querys.isShow;
      state.isApproved = querys.isApproved;
      state.title = `实名认证审核${querys.afterTitle || ""}`;

      if (row) {
        state.form = { ...row };
      }

      return new Promise((resolve, reject) => {
        state.resolve = resolve;
        state.reject = reject;
      });
    }

    /** 处理审核操作 */
    function handleVerify(verified) {
      if (!formRef.value) return;

      // 如果是拒绝审核，需要验证备注是否填写
      if (!verified) {
        formRef.value.validateField("remarks", (error) => {
          if (error) {
            messageError("请填写拒绝原因");
            return;
          }
          submitVerify(verified);
        });
      } else {
        submitVerify(verified);
      }
    }

    /** 提交审核 */
    function submitVerify(verified) {
      const action = verified ? "通过" : "拒绝";
      const type = verified ? "success" : "warning";

      ElMessageBox.confirm(
        `确定要${action}用户 "${
          state.form.userId?.username || ""
        }" 的实名认证审核吗？`,
        "审核确认",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: type,
        }
      )
        .then(() => {
          state.loading = true;

          const verificationId = state.form.id || state.form._id;
          if (!verificationId) {
            messageError("无法获取认证记录ID");
            state.loading = false;
            return;
          }

          verificationsApi
            .verifyUser(verificationId, {
              verified,
              remarks: state.form.remarks,
            })
            .then(() => {
              messageSuccess(`审核${action}成功`);
              state.dialogVisible = false;
              state.resolve();
            })
            .catch((err) => {
              console.error(`审核${action}失败`, err);
              messageError(err.message || `审核${action}失败`);
            })
            .finally(() => {
              state.loading = false;
            });
        })
        .catch(() => {
          // 用户取消操作
        });
    }

    /** 取消按钮 */
    function cancel() {
      state.dialogVisible = false;
      state.reject();
    }

    return {
      formRef,
      ...toRefs(state),
      initData,
      handleVerify,
      cancel,
    };
  },
});
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
  .el-button {
    margin-left: 10px;
  }
}
</style> 